package controller

import (
	"encoding/json"
	"gobase/app/service"
	"gobase/util"
	"net/http"

	"github.com/gin-gonic/gin"
)

//首页控制器
type IndexController struct {
	BaseController
}

//路由注册
func (ctl *IndexController) Router(router *gin.Engine) {
	router.GET("/index", ctl.index)
	router.GET("/", ctl.index)
	router.GET("/welcome", ctl.welcome)
	router.GET("/myinfo", ctl.myinfo)
	router.GET("/getMenus", ctl.getMenus)
	router.GET("/changePwd", ctl.changePwd)
	router.POST("/changePwd", ctl.changePwd)
}

//首页
func (ctl *IndexController) index(c *gin.Context) {
	currUser := util.GetCurrLoginUser(c)
	navList := service.NewResourceService(c).GetNav(util.GetCurrLoginUID(c))
	c.HTML(http.StatusOK, "index.html", gin.H{
		"title":        "index",
		"loginAccount": currUser,
		"navList":      navList,
	})
}

//默认页面
func (ctl *IndexController) welcome(c *gin.Context) {
	c.HTML(http.StatusOK, "welcome.html", gin.H{
		"title": "我的桌面",
	})
}

//个人信息
func (ctl *IndexController) myinfo(c *gin.Context) {
	uid := util.GetCurrLoginUID(c)
	uInfo, _ := service.NewUserService(c).GetMapByID(uid)
	c.HTML(http.StatusOK, "myinfo.html", gin.H{
		"title":    "个人信息",
		"user":     uInfo,
		"roleList": service.NewRoleUserService(c).GetRolesByUid(int64(uid)),
	})
}

//获取顶部菜单
func (ctl *IndexController) getMenus(c *gin.Context) {
	menuList := service.NewResourceService(c).GetMenu(util.GetCurrLoginUID(c))
	menuJSONList, _ := json.Marshal(menuList)
	ctl.ResponseJSON(c, true, "", string(menuJSONList))
}

//修改登录密码
func (ctl *IndexController) changePwd(c *gin.Context) {
	if ctl.IsPost(c.Request.Method) {
		oldPwd := c.PostForm("oldpwd")
		newPwd := c.PostForm("newpwd")
		uid := util.GetCurrLoginUID(c)

		if oldPwd == "" {
			ctl.ResponseJSON(c, false, "旧密码不允许为空！")
		}
		if newPwd == "" || len(newPwd) < 6 {
			ctl.ResponseJSON(c, false, "新密码不允许为空且最少6个字符！")
		}
		if err := service.NewUserService(c).ChangePwd(uid, oldPwd, newPwd); err != nil {
			ctl.ResponseJSON(c, false, err.Error())
		}
		ctl.ResponseJSON(c, true, "成功修改登录密码！")
	} else {
		c.HTML(http.StatusOK, "changepwd.html", gin.H{
			"title":        "修改登录密码",
			"loginAccount": util.GetCurrLoginUser(c),
		})
	}
}
